package com.sykj.cloud.log.mq;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.sykj.cloud.system.api.domain.LogError;
import com.sykj.cloud.log.service.ILogErrorService;
import groovy.util.logging.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author Mr.will
 * @date 2021/3/30 13:21
 * @Desc 错误日志记录处理
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = "${mq.logger.topic}",
        consumerGroup = "${mq.logger.consumer.group.name}" //,messageModel = MessageModel.CLUSTERING 默认就是集群模式
        )
public class LoggerErrorMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    ILogErrorService errorService;


    @Override
    public void onMessage(MessageExt messageExt) {
        //1. 解析消息内容
        try {
            String body = new String(messageExt.getBody(),"UTF-8");
            System.out.println(body);
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            // 设置浏览器信息
            String UA=request.getHeader("User-Agent");
            LogError log=new LogError();
            log.setUserAgent(UA);
            UserAgent ua = UserAgentUtil.parse(UA);
            // 设置浏览器类型
            log.setBrowserType(ua.getBrowser().toString());
            log.setDeviceOs(ua.getPlatform().toString());

//            LogError error=new LogError();
//            error.setErrorType(LogErrorType.PARAMETER_ERROR.code());
//            error.setName("");
//            errorService.insertLogError(error);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
